import type { Router } from "vue-router";
import { tokenUtils } from "@/utils";

const { VITE_LOGIN_PATH } = import.meta.env;

export const createPermissionGuard = (router: Router) => {
  router.beforeEach(async (to, form, next) => {
    console.log("form: ", form, "\nto", to);

    const token = tokenUtils.get();
    // 已登录状态跳转登录页，跳转至首页
    if (token && to.path === VITE_LOGIN_PATH) {
      console.log("已登录状态跳转登录页，跳转至首页");
      next({ path: "/" });
    }
    // 未登录状态进入登录页，跳转至登录页
    else if (!token && to.path === VITE_LOGIN_PATH) {
      console.log("未登录状态进入登录页");
      next();
    }
    // 未登录状态进入非登录页，跳转至登录页并携带参数
    else if (!token) {
      console.log("未登录状态进入非登录页，跳转至登录页并携带参数");
      next({
        path: VITE_LOGIN_PATH,
        query: { ...to.query, redirect: to.path },
      });
    }
    // 已登录状态
    else {
      next();
      tokenUtils.refresh();
    }
  });
};
